package handlers

import (
	"context"
	"fmt"
	"log"
	"net/http"
	"time"

	"demo2/server/services"

	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
)

// ChatHandler 聊天处理器
type ChatHandler struct {
	chatService *services.ChatService
	upgrader    websocket.Upgrader
}

// NewChatHandler 创建新的聊天处理器
func NewChatHandler(chatService *services.ChatService) *ChatHandler {
	return &ChatHandler{
		chatService: chatService,
		upgrader: websocket.Upgrader{
			CheckOrigin: func(r *http.Request) bool {
				return true // 允许所有来源，生产环境应该更严格
			},
		},
	}
}

// SendMessageRequest 发送消息请求
type SendMessageRequest struct {
	SessionID string `json:"sessionId" binding:"required"`
	Message   string `json:"message" binding:"required"`
}

// SendMessageResponse 发送消息响应
type SendMessageResponse struct {
	ID        string `json:"id"`
	SessionID string `json:"sessionId"`
	Role      string `json:"role"`
	Content   string `json:"content"`
	Timestamp string `json:"timestamp"`
}

// SendMessage 发送消息
func (h *ChatHandler) SendMessage(c *gin.Context) {
	log.Printf("[HTTP-HANDLER] 📨 收到发送消息请求，来源IP: %s", c.ClientIP())
	
	var req SendMessageRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		log.Printf("[HTTP-HANDLER] ❌ 请求参数绑定失败: %v", err)
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	log.Printf("[HTTP-HANDLER] 📋 请求参数: 会话ID=%s, 消息长度=%d", req.SessionID, len(req.Message))
	log.Printf("[HTTP-HANDLER] 📝 用户消息内容: %s", req.Message)

	// 调用聊天服务
	log.Printf("[HTTP-HANDLER] 🔄 调用聊天服务处理消息...")
	response, err := h.chatService.SendMessage(c.Request.Context(), req.SessionID, req.Message)
	if err != nil {
		log.Printf("[HTTP-HANDLER] ❌ 聊天服务处理失败: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "发送消息失败"})
		return
	}

	log.Printf("[HTTP-HANDLER] ✅ 聊天服务处理成功，响应ID: %s", response.ID)

	// 返回响应
	responseData := SendMessageResponse{
		ID:        response.ID,
		SessionID: response.SessionID,
		Role:      response.Role,
		Content:   response.Content,
		Timestamp: response.Timestamp.Format("2006-01-02 15:04:05"),
	}
	
	log.Printf("[HTTP-HANDLER] 📤 返回响应，内容长度: %d", len(responseData.Content))
	c.JSON(http.StatusOK, responseData)
}

// SendStreamMessage 发送流式消息
func (h *ChatHandler) SendStreamMessage(c *gin.Context) {
	var req SendMessageRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	// 设置SSE头部
	c.Header("Content-Type", "text/event-stream")
	c.Header("Cache-Control", "no-cache")
	c.Header("Connection", "keep-alive")
	c.Header("Access-Control-Allow-Origin", "*")
	c.Header("Access-Control-Allow-Headers", "Cache-Control")

	// 创建响应通道
	responseChan := make(chan string, 100)
	ctx, cancel := context.WithTimeout(c.Request.Context(), 60*time.Second)
	defer cancel()

	// 启动流式响应
	go func() {
		defer close(responseChan)
		if err := h.chatService.SendStreamMessage(ctx, req.SessionID, req.Message, responseChan); err != nil {
			log.Printf("流式响应失败: %v", err)
		}
	}()

	// 发送SSE事件
	flusher, ok := c.Writer.(http.Flusher)
	if !ok {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "不支持流式响应"})
		return
	}

	for {
		select {
		case chunk, ok := <-responseChan:
			if !ok {
				// 发送结束事件
				fmt.Fprintf(c.Writer, "event: end\ndata: \n\n")
				flusher.Flush()
				return
			}
			// 发送数据块
			fmt.Fprintf(c.Writer, "event: data\ndata: %s\n\n", chunk)
			flusher.Flush()
		case <-ctx.Done():
			fmt.Fprintf(c.Writer, "event: error\ndata: 请求超时\n\n")
			flusher.Flush()
			return
		}
	}
}

// GetHistory 获取聊天历史
func (h *ChatHandler) GetHistory(c *gin.Context) {
	sessionID := c.Param("sessionId")
	if sessionID == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "sessionId是必需的"})
		return
	}

	messages, err := h.chatService.GetHistory(c.Request.Context(), sessionID)
	if err != nil {
		log.Printf("获取历史失败: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取历史失败"})
		return
	}

	// 转换为响应格式
	responses := make([]SendMessageResponse, len(messages))
	for i, msg := range messages {
		responses[i] = SendMessageResponse{
			ID:        msg.ID,
			SessionID: msg.SessionID,
			Role:      msg.Role,
			Content:   msg.Content,
			Timestamp: msg.Timestamp.Format("2006-01-02 15:04:05"),
		}
	}

	c.JSON(http.StatusOK, gin.H{"messages": responses})
}

// ClearHistory 清除聊天历史
func (h *ChatHandler) ClearHistory(c *gin.Context) {
	sessionID := c.Param("sessionId")
	if sessionID == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "sessionId是必需的"})
		return
	}

	err := h.chatService.ClearHistory(c.Request.Context(), sessionID)
	if err != nil {
		log.Printf("清除历史失败: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "清除历史失败"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "历史已清除"})
}

// WebSocketMessage WebSocket消息格式
type WebSocketMessage struct {
	Type      string `json:"type"`
	SessionID string `json:"sessionId,omitempty"`
	Message   string `json:"message,omitempty"`
	Content   string `json:"content,omitempty"`
	Role      string `json:"role,omitempty"`
	Timestamp string `json:"timestamp,omitempty"`
}

// WebSocketHandler WebSocket处理器
func (h *ChatHandler) WebSocketHandler(c *gin.Context) {
	sessionID := c.Param("sessionId")
	if sessionID == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "sessionId是必需的"})
		return
	}

	// 升级到WebSocket连接
	conn, err := h.upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		log.Printf("WebSocket升级失败: %v", err)
		return
	}
	defer conn.Close()

	log.Printf("WebSocket连接建立，会话ID: %s", sessionID)

	// 处理WebSocket消息
	for {
		var msg WebSocketMessage
		err := conn.ReadJSON(&msg)
		if err != nil {
			log.Printf("读取WebSocket消息失败: %v", err)
			break
		}

		if msg.Type == "message" && msg.Message != "" {
			// 创建响应通道
			responseChan := make(chan string, 100)
			ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)

			// 启动流式响应
			go func() {
				defer close(responseChan)
				defer cancel()
				if err := h.chatService.SendStreamMessage(ctx, sessionID, msg.Message, responseChan); err != nil {
					log.Printf("WebSocket流式响应失败: %v", err)
					responseChan <- fmt.Sprintf("处理消息失败: %v", err)
				}
			}()

			// 发送流式响应
			fullResponse := ""
			for chunk := range responseChan {
				fullResponse += chunk
				err = conn.WriteJSON(WebSocketMessage{
					Type:      "stream",
					SessionID: sessionID,
					Content:   chunk,
					Role:      "assistant",
					Timestamp: time.Now().Format("2006-01-02 15:04:05"),
				})
				if err != nil {
					log.Printf("发送WebSocket流式响应失败: %v", err)
					cancel()
					break
				}
			}

			// 发送结束标记
			if fullResponse != "" {
				err = conn.WriteJSON(WebSocketMessage{
					Type:      "end",
					SessionID: sessionID,
					Content:   fullResponse,
					Role:      "assistant",
					Timestamp: time.Now().Format("2006-01-02 15:04:05"),
				})
				if err != nil {
					log.Printf("发送WebSocket结束消息失败: %v", err)
					break
				}
			}

			cancel()
		}
	}
}
